#include "widget.h"
#include "ui_widget.h"

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);

    table=TD_EVENT_LOG;

    ui->logNames->addItems(logNames);

    model=new QSqlQueryModel(this);
    ui->tableView->setModel(model);

    updateSources();
    updateMachineNames();
}

Widget::~Widget()
{
    delete ui;
}

void Widget::updateSources()
{
    if(ui->sources->count() != 0)
        ui->sources->clear();
    auto items=sp_getCategory("Source",table,"Date",Today);
    if(!items.isEmpty())
        ui->sources->addItems(items);
}

void Widget::updateMachineNames()
{
    if(ui->machineNames->count() != 0)
        ui->machineNames->clear();

    auto items=sp_getCategory("MachineName",table,"Date",Today);
    if(!items.isEmpty())
        ui->machineNames->addItems(items);
}

void Widget::updateView()
{
    QString sql=QString("select Type,Date,Time,Category,InstanceId,Message from %1"
" where LogName='%2' AND Source='%3' AND MachineName='%4'"
" ORDER BY Time Desc")
            .arg(table)
            .arg(ui->logNames->currentText())
            .arg(ui->sources->currentText())
            .arg(ui->machineNames->currentText());
    // qDebug() << sql;
    model->setQuery(sql);
    setHeaderData();
}

void Widget::setHeaderData()
{
    model->setHeaderData(0,Qt::Horizontal,QStringLiteral("类型"));
    model->setHeaderData(1,Qt::Horizontal,QStringLiteral("日期"));
    model->setHeaderData(2,Qt::Horizontal,QStringLiteral("时间"));
    model->setHeaderData(3,Qt::Horizontal,QStringLiteral("类别"));
    model->setHeaderData(4,Qt::Horizontal,QStringLiteral("事件ID"));
    model->setHeaderData(5,Qt::Horizontal,QStringLiteral("事件"));
}

void Widget::on_btn_submit_clicked()
{
    updateView();
}

void Widget::on_tableView_clicked(const QModelIndex &index)
{
    if(index.isValid())
    {
        QString message=index.sibling(index.row(),5).data().toString();
        ui->message->setPlainText(message);
    }
}
